package com.gupao.rpc.zk;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class RegistryCenterImpl implements IRegistryCenter {

    private CuratorFramework curatorFramework;
    {
        curatorFramework = CuratorFrameworkFactory.builder().connectString(ZKConfig.CONNECT_STR)
                .retryPolicy(new ExponentialBackoffRetry(1000,10))
                .sessionTimeoutMs(4000)
                .build();

        curatorFramework.start();

    }

    @Override
    public void register(String serviceName, String address) {
        try {
            String serviceNamePath = ZKConfig.REGISTRY_PATH+"/"+serviceName;
            if(curatorFramework.checkExists().forPath(serviceNamePath)==null){
                curatorFramework.create().creatingParentsIfNeeded().
                        withMode(CreateMode.PERSISTENT).forPath(serviceNamePath,"0".getBytes());
//                curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(serviceNamePath,"0".getBytes());
            }
            String addressPath = serviceNamePath+"/"+address;
            String addrssNode = curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(addressPath,"0".getBytes());
            System.out.println("服务注册成功--->"+addrssNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
